'use strict';

//实现付费数据手动回传

var vk; // 全局vk实例
var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符

/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
	},
	_after: async function(options) {
		let {
			err,
			res
		} = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},

	backHaulDouYin: async function(data) {
		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let {
			invite_code
		} = data;
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		// 业务逻辑开始-----------------------------------------------------------
		//获取现在的时间
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "a_recharge", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "douyin",
				invite_code: invite_code,
				user_register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无巨量推广记录"
			}
		}
		const clickid = list[0].clickid;
		console.log("69行clickid：", clickid);
		res.jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
		res.jlresult = await uniCloud.httpclient.request(res.jlurl, {
			method: 'POST',
			data: {
				"event_type": "active_pay",
				"context": {
					"ad": {
						"callback": clickid, //callback 这里需要填写的就是从启动参数里获取的 clickid
					}
				},
				"properties": {
					"pay_amount": total_fee, //回传付费金额
				},
				//附加属性回传http://event-manager.oceanengine.com/docs/8650/all_properties/
				"timestamp": _add_time
			},
			contentType: 'json',
			dataType: 'json'
		})

		// 回传记录入库
		let addhc1 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "tiktok",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: res.jlresult.data,
			time: _add_time,
			time_str: _add_time_str
		})

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/pages/pub/callback.test 前端调用的url参数地址
	 *  回传支付事件给快手广告平台
	 */
	backHaulKuaiShou: async function(data) {
		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let {
			invite_code
		} = data;
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		// 业务逻辑开始-----------------------------------------------------------
		let nows = new Date().getTime()
		let purchase_amount = Math.floor(Math.random() * 3990) + 990;
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "a_recharge", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "kuaishou",
				invite_code: invite_code,
				user_register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无快手推广记录"
			}
		}
		// console.log("117行list：", list);
		const clickid = list[0].clickid;
		let ksurl =
			"http://ad.partner.gifshow.com/track/activate?event_type=3&purchase_amount=" +
			purchase_amount + "&event_time=" + nows + "&callback=" + clickid
		let kshuichuan_result = await uniCloud.httpclient.request(ksurl, {
			method: 'GET',
			data: {},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})
		//回传返回结果为什么要加一个code？因为巨量广告的回传返回值有code,为方便后续通过code来统计回传成功次数，故在快手处也加一个code参数
		//快手返回成功形式为"result":1,"host-name":"ad-rs-bjmt-ad467.idcyz.hb1.kwaidc.com"
		if (kshuichuan_result.data.result == 1) {
			kshuichuan_result.data.code = 0
		}

		// 回传记录入库
		let addhc2 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "kuaishou",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: kshuichuan_result.data,
			time: _add_time,
			time_str: _add_time_str
		})

		// 业务逻辑结束-----------------------------------------------------------
		return kshuichuan_result.data;
	},
	/**
	 * @param {Object} data
	 *回传支付事件给UC广告平台
	 */
	backHaulUc: async function(data) {
		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let {
			invite_code
		} = data;
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		// 业务逻辑开始-----------------------------------------------------------
		let nows = new Date().getTime()
		let purchase_amount = Math.floor(Math.random() * 99) + 1; //金额单位转为元，且保留2位小数
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "a_recharge", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "uc",
				invite_code: invite_code,
				user_register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无uc推广记录"
			}
		}
		const clickid = list[0].clickid;
		let ucurl = clickid + "&type=66&money=" + purchase_amount + "&event_time=" + nows
		let uchuichuan_result = await uniCloud.httpclient.request(ucurl, {
			method: 'GET',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})
		uchuichuan_result.data.code = 0

		// 回传记录入库
		let uc_hc_log0 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "uc",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: uchuichuan_result.data,
			time: _add_time,
			time_str: _add_time_str
		})
		// console.log("191行：", uchuichuan_result);
		// 业务逻辑结束-----------------------------------------------------------
		return uchuichuan_result.data;
	},
	/**
	 * @param {Object} data
	 *回传支付事件给腾讯广告平台
	 */
	backHaulTengXun: async function(data) {
		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let { invite_code } = data;
		let { uid } = this.getClientInfo(); // 获取客户端信息
		// 业务逻辑开始-----------------------------------------------------------
		// 回传支付事件给腾讯广告平台
		let nows = new Date().getTime()
		let ts_10 = Math.round(new Date().getTime() / 1000).toString();
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "a_recharge", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "tengxun",
				invite_code: invite_code,
				user_register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无腾讯推广记录"
			}
		}
		// console.log("198行list：", list);
		const clickid = list[0].clickid;
		// 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
		//回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
		let tengxunurl =
			"http://tracking.e.qq.com/conv/web?clickid=" + clickid + "&action_time=" + ts_10 +
			"&action_type=PURCHASE&value=" + total_fee + "&link=tracking.e.qq.com";
		let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
			method: 'GET',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})
		tengxunhuichuan_result.data.code = 0
		// 回传记录入库
		let uc_hc_log = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "tengxun",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: tengxunhuichuan_result.data,
			time: _add_time,
			time_str: _add_time_str
		})
		// 业务逻辑结束-----------------------------------------------------------
		return tengxunhuichuan_result.data;
	},
	/**
	 * @param {Object} data
	 *回传支付事件给百度广告平台
	 */
	backHaulBaiDu: async function(data) {
		var time = vk.pubfn.getCommonTime(new Date());
		var todayStart = time.todayStart;
		var todayEnd = time.todayEnd;

		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		// console.log("uid=", uid);
		// console.log("invite_code=", data.invite_code);
		// 业务逻辑开始-----------------------------------------------------------
		let nows = new Date().getTime()
		let {
			baidu_token,
			invite_code
		} = data;
		console.log("todayStart=", todayStart);
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "uni-id-users", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "baidu",
				invite_code: invite_code,
				register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无百度推广记录"
			}
		}
		const clickid = list[0].clickid;
		// const clickid = "P1fvPjRdPWnknjmLn1T4nWmkPdtLnH-xn-t1nj0sg1PxPH6kP103nWmvn1fv";
		console.log("clickid=", clickid);
		// 回传支付事件给百度
		let baiduurl = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData"
		let baiduhuichuan_result = await uniCloud.httpclient.request(baiduurl, {
			method: 'POST',
			data: {
				"token": baidu_token, //无忧短剧token
				"conversionTypes": [{
					"logidUrl": "bd_vid=" + clickid,
					"newType": 118, //付费观剧，参考：https://dev2.baidu.com/content?sceneType=0&pageId=101207&nodeId=655
					"convertValue": total_fee, //转化金额，单位分，https://dev2.baidu.com/content?sceneType=0&pageId=101211&nodeId=658&subhead=
					"attributeSource": 0, //（转化来源：百度（0），自然流量（1），竞媒（2））
					"interactionsType": 1 //（归因请求方式，点击(1), 播放(2), 关注(3), 分享(4), 点赞(5), 曝光（6）不传使用1，默认为点击归因
				}]
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})


		baiduhuichuan_result.data.code = 0
		// 回传记录入库
		let uc_hc_log = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "baidu",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: baiduhuichuan_result.data,
			time: _add_time,
			time_str: _add_time_str
		})

		// 业务逻辑结束-----------------------------------------------------------
		return baiduhuichuan_result.data;
	},
	/**
	 * @param {Object} data
	 *回传支付事件给opp广告平台
	 */
	backHaulOppo: async function(data) {
		var total_fee = Math.floor(Math.random() * 3990) + 990;
		var _add_time = new Date().getTime();
		var _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
		let res = { code: 0, msg: '' };
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		let { owner_id, api_id, api_key, invite_code } = data;
		// 业务逻辑开始-----------------------------------------------------------
		const crypto = require('crypto');
		const sha1 = crypto.createHash('sha1');
		// let owner_id = owner_id;
		// let api_id = api_id;
		// let api_key = api_key;
		let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
		let beforesha1 = api_id + api_key + times;
		let sign = sha1.update(beforesha1).digest('hex');
		// console.log("sign=", sign);

		//1.加密 
		let input = owner_id + "," + api_id + "," + times + "," + sign;
		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		// console.log("output=", output);
		//获取触点信息
		let list = await vk.baseDao.sample({
			dbName: "uni-id-users", // 表名
			size: 1, // 随机条数
			whereJson: { // 条件
				tg_pt: "oppo",
				invite_code: invite_code,
				register_date: _.gt(todayStart)
			}
		});
		if (list.length == 0) {
			return {
				code: "-1",
				msg: "回传失败，充值记录表无opp推广记录"
			}
		}
		const clickid = list[0].clickid;
		// console.log("clickid=", clickid);
		// 回传支付事件给OPPO
		let oppourl = "https://sapi.ads.oppomobile.com/v1/clue/sendData"
		let oppohuichuan_result = await uniCloud.httpclient.request(oppourl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: "Bearer " + output
			},
			data: {
				"ip": list[0].ip || "127.0.0.1",
				"transformType": 101,
				"ownerId": owner_id,
				"pageId": list[0].pageId || "1",
				"tid": clickid,
				"items": [{
						"column": "姓名",
						"desc": "姓名输入框",
						"ifNeed": true,
						"type": "1",
						"value": "小红"
					},
					{
						"column": "电话",
						"desc": "电话",
						"ifNeed": true,
						"type": "3",
						"value": "18783687596"
					}
				],
				"lbid": "1_0_0"
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})

		oppohuichuan_result.data.code = 0

		// 回传记录入库
		let uc_hc_log = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "oppo",
			user_id: "手动回传",
			agent_id: invite_code,
			clickid: clickid,
			money: total_fee,
			result: oppohuichuan_result.data,
			time: _add_time,
			time_str: _add_time_str
		})

		// 业务逻辑结束-----------------------------------------------------------
		// console.log("405行：", oppohuichuan_result);
		return oppohuichuan_result.data;
	},
};

module.exports = cloudObject;
